function Upload() {
};

Upload.init = function(browse_id, upload_url, callback, opts) {
  var SWFUPLOAD_DIR = '../3rd_party/swfupload/';
  
  var settings = {
    flash_url : SWFUPLOAD_DIR + 'swfupload.swf',
    flash9_url : SWFUPLOAD_DIR + 'swfupload_fp9.swf',
    upload_url : upload_url,
    post_params : (opts && opts.post_params) ? opts.post_params : null,
    file_size_limit : (opts && opts.file_size_limit) ? opts.file_size_limit : '100MB',
    file_types : (opts && opts.file_types) ? opts.file_types : '*.jpg;*.jpeg;*.png;*.gif',
    file_types_description : (opts && opts.file_types_description) ? opts.file_types_description : 'Image Files',
    file_upload_limit : (opts && opts.file_upload_limit) ? opts.file_upload_limit : 0,
    file_queue_limit : (opts && opts.file_queue_limit) ? opts.file_queue_limit : 0,
    custom_settings : {
      unique_id : Utils.unique(),
      cancel_id : (opts && opts.cancel_id) ? opts.cancel_id : null,
      pos : (opts && opts.pos) ? opts.pos : Utils.find_pos(document.getElementById(browse_id)),
      file_processed : [],
      file_total : [],
      srv_objs: [],
      srv_err: false,
      callback: callback,
      debug: (opts && opts.debug) ? opts.debug : 0
    },
    debug : false,

    // Button settings
    button_image_url : (opts && opts.button_image_url) ? opts.button_image_url : SWFUPLOAD_DIR + 'browse.png',
    button_width : (opts && opts.button_width) ? opts.button_width : 94,
    button_height : (opts && opts.button_height) ? opts.button_height : 25,
    button_placeholder_id : browse_id,
//    button_text: '<span class="theFont">Hello</span>',
//    button_text_style: '.theFont { font-size: 16; }',
    button_text_left_padding : 0,
    button_text_top_padding : 0,

    // The event handler functions are defined in handlers.js
    swfupload_preload_handler : preLoad,
    swfupload_load_failed_handler : loadFailed,
    file_queued_handler : fileQueued,
    file_queue_error_handler : fileQueueError,
    file_dialog_complete_handler : fileDialogComplete,
    upload_start_handler : (opts && opts.upload_start_handler) ? opts.upload_start_handler : function(file) { },
    upload_progress_handler : uploadProgress,
    upload_error_handler : uploadError,
    upload_success_handler : uploadSuccess,
    upload_complete_handler : uploadComplete,
    queue_complete_handler : queueComplete // Queue plugin event
  };
  return new SWFUpload(settings);
};

function preLoad() {
  if (!this.support.loading) {
    alert("You need the Flash Player 9.028 or above to use SWFUpload.");
    return false;
  }
}

function loadFailed() {
  alert("Something went wrong while loading SWFUpload. If this were a real application we'd clean up and then give you an alternative");
}

function fileQueued(file) {
  try {
    this.customSettings.file_total[this.customSettings.file_total.length] = file;
  } catch (ex) {
    this.debug(ex);
  }
}

function fileQueueError(file, errorCode, message) {
  try {
    if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
      alert("You have attempted to queue too many files.\n" + (message === 0 ? "You have reached the upload limit." : "You may select " + (message > 1 ? "up to " + message + " files." : "one file.")));
      return;
    }
    switch (errorCode) {
    case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
      alert(file.name + ": File is too big.");
      this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
      break;
    case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
      alert(file.name + ": Cannot upload Zero Byte files.");
      this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
      break;
    case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
      alert(file.name + ": invalid File Type.");
      this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
      break;
    default:
      if (file !== null) {
        alert(file.name + ": Unhandled Error");
      }
      this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
      break;
    }
  } catch (ex) {
    this.debug(ex);
  }
}

function fileDialogComplete(numFilesSelected, numFilesQueued) {
  var _self = this;
  try {
    if (numFilesSelected > 0 && numFilesQueued > 0 && 
        (numFilesSelected <= this.settings.file_upload_limit || this.settings.file_upload_limit == 0) && 
        (numFilesQueued <= this.settings.file_queue_limit || this.settings.file_queue_limit == 0)) {
      if (this.customSettings.cancel_id) {
        document.getElementById(this.customSettings.cancel_id).disabled = false;
      }
      
      if (window.__ns) {
        for (var idx in window.__ns) {
          var obj = window.__ns[idx];
          obj.close();
        }
      } else {
        window.__ns = [];
      }

      var html = '<div id="dialog_' + this.customSettings.unique_id + '" style="display: none; z-index: 9999;">' + 
                   '<div id="text_' + this.customSettings.unique_id + '"></div>' +
                   '<div>&nbsp;</div>' + 
                   '<div id="progress_' + this.customSettings.unique_id + '"></div>'+ 
                 '</div>';
      $('body').append(html);
      $('#dialog_' + this.customSettings.unique_id).dialog({
        position: {
          my: 'left+' + this.customSettings.pos[0] + ' top+' + this.customSettings.pos[1],
          at: 'left top',
          of: 'body'
        },
        buttons: {
          'Close': function() { 
            $(this).dialog('close');
            _self.customSettings.callback(_self.customSettings.srv_objs, _self.customSettings.srv_err);
          }
        }
      });
      $(".ui-dialog-titlebar").hide();
      $(".ui-dialog-buttonpane").hide();
      $('#text_' + this.customSettings.unique_id).empty();
      $('#text_' + this.customSettings.unique_id).append('Starting...');
      $('#progress_' + this.customSettings.unique_id).progressbar();
      $('#progress_' + this.customSettings.unique_id).progressbar('value', 0);
      this.customSettings.file_processed = [];
      this.customSettings.srv_objs = [];
      this.customSettings.srv_err = false;
      
      /* I want auto start the upload and I can do that here */
      this.startUpload();
    }
  } catch (ex) {alert(ex + this.customSettings.browseBtn);
    this.debug(ex);
  }
}

function uploadProgress(file, bytesLoaded, bytesTotal) {
  var total, progressed, percent, text;
  try {
    total = 0;
    for (var idx in this.customSettings.file_total) {
      var obj = this.customSettings.file_total[idx];
      total += parseFloat(obj.size, 10);
    }
    
    processed = 0;
    for (var idx in this.customSettings.file_processed) {
      var obj = this.customSettings.file_processed[idx];
      processed += parseFloat(obj.size, 10);
    }
    processed += parseFloat(bytesLoaded, 10);
    
    percent = Math.ceil((processed / total) * 100);
    text = 'Uploading Files ' + (this.customSettings.file_processed.length + 1) + '/' + this.customSettings.file_total.length + ' (' + accounting.formatNumber(parseInt(processed / 1000, 10)) + ' of ' + accounting.formatNumber(parseInt(total / 1000, 10)) + 'kb' + ')...';
    
    $('#text_' + this.customSettings.unique_id).empty();
    $('#text_' + this.customSettings.unique_id).append(text);
    $('#progress_' + this.customSettings.unique_id).progressbar('value', percent);
  } catch (ex) {
    this.debug(ex);
  }
}

function uploadSuccess(file, serverData) {
  if (this.customSettings.debug == 1) {
    alert(serverData);
  }
  try {
    this.customSettings.file_processed[this.customSettings.file_processed.length] = file;
    var obj = Utils.parse(serverData);
    if (typeof obj != 'object' && serverData != '') {
      window.__ns[window.__ns.length] = Utils.message(serverData, 'error');
      this.customSettings.srv_err = true;
    } else {
      this.customSettings.srv_objs[this.customSettings.srv_objs.length] = obj;
    }
  } catch (ex) {
    alert(ex);
    this.debug(ex);
  }
}

function uploadError(file, errorCode, message) {
  try {
    switch (errorCode) {
    case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
      progress.setStatus("Upload Error: " + message);
      this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
      break;
    case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
      progress.setStatus("Upload Failed.");
      this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
      break;
    case SWFUpload.UPLOAD_ERROR.IO_ERROR:
      progress.setStatus("Server (IO) Error");
      this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
      break;
    case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
      progress.setStatus("Security Error");
      this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
      break;
    case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
      progress.setStatus("Upload limit exceeded.");
      this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
      break;
    case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
      progress.setStatus("Failed Validation.  Upload skipped.");
      this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
      break;
    case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
      // If there aren't any files left (they were all cancelled) disable the cancel button
      if (this.getStats().files_queued === 0) {
        if (this.customSettings.cancel_id) {
          document.getElementById(this.customSettings.cancel_id).disabled = true;
        }
      }
      progress.setStatus("Cancelled");
      progress.setCancelled();
      break;
    case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
      progress.setStatus("Stopped");
      break;
    default:
      progress.setStatus("Unhandled Error: " + errorCode);
      this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
      break;
    }
  } catch (ex) {
    this.debug(ex);
  }
}

function uploadComplete(file) {
  if (this.getStats().files_queued === 0) {
    if (this.customSettings.cancel_id) {
      document.getElementById(this.customSettings.cancel_id).disabled = true;
    }
  }
}

function queueComplete(numFilesUploaded) {
  $(".ui-dialog-buttonpane").show();
  
  text = 'Uploaded ' + (numFilesUploaded) + '/' + this.customSettings.file_total.length;
  $('#text_' + this.customSettings.unique_id).empty();
  $('#text_' + this.customSettings.unique_id).append(text);
  
  this.customSettings.file_processed = [];
  this.customSettings.file_total = [];
};